package com.datastructure.test.numberoneofbinary;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class NumberOfOneOfBinary {

    public static void main(String[] args) {
        NumberOfOneOfBinary numberOfOneOfBinary = new NumberOfOneOfBinary();
        int i = numberOfOneOfBinary.NumberOf1(-2147483648);
        System.out.println(i);
    }

    public int NumberOf1(int n) {
        if(n==0){
            return 0;
        }
        if(n==-2147483648){
            return 1;
        }
        int result;
        int next=0;
        String str="";
        Map<Integer, String> resolve = resolve(n, 2);
        Iterator<Integer> iterator = resolve.keySet().iterator();
        if (iterator.hasNext()) {
            next = iterator.next();
            str=resolve.get(next);
        }
        if(n>0){
            result=next;
        }else {
            result=(next+(32-str.length()));
        }
        return result;
    }

    public Map<Integer,String> resolve(int M, int N){
        Map<Integer,String> map = new HashMap<>();
        int sum = 0;
        int m = Math.abs(M);
        String res = "0123456789ABCDEF";
        StringBuilder stringBuilder = new StringBuilder();
        while (m>0){
            if(m%N==1){
                sum++;
            }
            stringBuilder.append(res.charAt(m%N));
            m=m/N;
        }
        map.put(sum,stringBuilder.toString());
        return map;
    }
}
